const util = require("../../../utils/util");
var app = getApp()
Page({
  data: {
    markers: [{
      iconPath: "/images/nav/map.png",
      latitude: 0,
      longitude:0,
      name: '',   //大厦名称
      address: '', //地图完整地址
    }],
    said: 0,
    addressData: {Address: '', Mobile: '',Consignee: ''},
    cityList: [],
    CountyList: [],
    address2: '',  //门牌地址
    selRegion: {provinceId: 0, provinceName:'请选择', cityId: 0, cityName: '请选择',countyId: 0, countyName:'请选择'} //选择的区域
  },

  onLoad: function (e) {
    this.getProvince()
    if (e.said) {
      this.getShipAddress(e.said)  
    }    
  },
  //保存
  bindSave: function (e) {
    var that = this;
    var consignee = e.detail.value.consignee;
    var address = e.detail.value.address;
    var mobile = e.detail.value.mobile;
    var markers = that.data.markers[0];
    var said = that.data.said ? parseInt(that.data.said) : 0;
    var regionId = parseInt(this.data.selRegion.countyId);
    if (consignee == "") {
      util.showToast('请填写联系人姓名');
      return;
    }
    if (mobile == "") {
      util.showToast('请填写手机号码');
      return;
    }
    if(regionId <= 0){
      util.showToast('请重新选择收货地址');
      return;
    }
   
    if (address == "") {
      util.showToast('请填写详细地址');         
      return;
    }
    if(e.detail.value.address2 !=''){
      address += e.detail.value.address2;
    }
    address = address.replace(that.data.selDistrict, '');
    var action = said > 0 ? '/api/user/editShipAddress' : '/api/user/addShipAddress'
    wx.request({
      url: app.globalData.host + action,
      data: {
        uid: app.globalData.userInfo.Uid,
        said: said,
        regionid: regionId,
        consignee: consignee,
        address: address,
        mobile: mobile,
        isDefault: 1,
        lat: markers.latitude,
        lng: markers.longitude
      },
      success: function (res) {
        if (res.data.Code != 0) {        
          util.showModal(res.data.Message);   
          return;
        }
        wx.navigateBack()
      }
    })
  },
  bindCancel: function () {
    wx.navigateBack({})
  },
  
  bindConsignee: function(e){
    var addressData = this.data.addressData;
    addressData.Consignee = e.detail.value;
    this.setData({
      addressData: addressData
    })
  },
  bindMobile: function(e){
    var addressData = this.data.addressData;
    addressData.Mobile = e.detail.value;
    this.setData({
      addressData: addressData
    })
  },
  //省值选择变化
  bindProvince: function (e) {
    var selIterm = this.data.provinces[e.detail.value]
    var provinceId = parseInt(e.detail.value) + 1
    this.setData({
      selProvince: selIterm,
      selProvinceIndex: provinceId,
      selCity: '请选择',
      selDistrict: '请选择'
    })
    this.getCityList(provinceId)//初始化市数据
  },  
  //市值选择
  bindCity: function (event) {
    var cityList = this.data.cityList
    var selIterm = this.data.citys[event.detail.value]
    for (var i = 0; i < cityList.length; i++) {
      if (selIterm == cityList[i].name) {
        var citysId = cityList[i].id
      }
    }
    this.setData({
      selCity: selIterm,
      selCityIndex: citysId,
      selDistrict: '请选择'
    })
    this.getCountyList(citysId)
  },
  //区县选择
  bindCounty: function (event) {
    var CountyList = this.data.CountyList
    var selIterm = this.data.districts[event.detail.value]
    for (var i = 0; i < CountyList.length; i++) {
      if (selIterm == CountyList[i].name) {
        var DistrictId = CountyList[i].id
      }
    }
    this.setData({
      selDistrict: selIterm,
      selDistrictIndex: DistrictId
    })
  },

  //设置地区数据
  setCountyList: function (cityName, countyName) {
    var CountyList = this.data.CountyList;
    for (let i = 0; i < CountyList.length; i++) {
      if (CountyList[i].name == countyName) {
        this.setData({
          selDistrict: countyName,
          selDistrictIndex: CountyList[i].id
        })
      }
    }
  },

  //获取省
  getProvince: function (e) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/ProvinceList',
      success: function (res) {
        var provincesArray = JSON.parse(res.data.Data)
        var pinkArray = [];
        for (var i = 0; i < provincesArray.length; i++) {
          pinkArray.push(provincesArray[i].name);
        }
        that.setData({
          provinces: pinkArray
        })
      }
    })
  },
  //获取市
  getCityList: function (provinceid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/CityList?provinceId=' + provinceid,
      success: function (res) {
        var cityList = JSON.parse(res.data.Data)
        var pinkCitys = [];
        for (var i = 0; i < cityList.length; i++) {
          pinkCitys.push(cityList[i].name);
        }
        that.setData({
          citys: pinkCitys,
          cityList: cityList
        })
      }
    })
  }, 
  //获取区县
  getCountyList: function (citysid) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/CityList?provinceId=' + citysid,
      success: function (res) {
        var CountyList = JSON.parse(res.data.Data)
        var pinkCounty = [];
        for (var i = 0; i < CountyList.length; i++) {
          pinkCounty.push(CountyList[i].name);
        }
        that.setData({
          districts: pinkCounty,
          CountyList: CountyList
        })
      }
    })
  }, 
 
  //获取地址信息
  getShipAddress: function(id){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/user/GetShipAddress?said=' + id + '&uid=' +  app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          let data = res.data.Data;
          let markers = that.data.markers;
          let selRegion = that.data.selRegion;
          markers[0].latitude = data.Latitude;
          markers[0].longitude = data.Longitude;
          selRegion.countyId= data.RegionId;
          that.setData({
            said: id,
            addressData: data,
            selRegion: selRegion,
            markers: markers          
          });
        } else {
          util.showModal('无法获取快递地址数据');
        }
      }
    })
  },
  deleteAddress: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除该收货地址吗？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.host + '/api/user/DelShipAddress',
            data: {
              uid: app.globalData.userInfo.Uid,
              said: id
            },
            success: (res) => {
              wx.navigateBack({})
            }
          })
        } else if (res.cancel) {
        }
      }
    })
  },
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    wx.stopPullDownRefresh();
  },
  
  //获取地理位置
  selectAdress: function (e) {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        console.log(res)
        var markers = that.data.markers;
        markers[0].latitude = res.latitude;
        markers[0].longitude = res.longitude;
        markers[0].name = res.name;
        markers[0].address = res.address;
        that.getRegion(res.latitude, res.longitude, res.name);
        that.setData({
          markers: markers,
        })
      },
      fail: function () {
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.userLocation']) {
              wx.authorize({
                scope: 'scope.userLocation',
                success(res) {}
              })
            }
          }
        })
      }
    })
  },
  //坐标转城市
  getRegion: function(lat,lng,address){
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Tool/GetRegionByGeo?lat=' + lat + '&lng=' + lng,
      success: function (res) {      
        if(res.data.Code == 0 ){
          var item = res.data.Data;
          if(item ==null){
            utils.showToast('地址未找到请更换');
            return;
          }
          var addressData = that.data.addressData;
          addressData.Address = address;
          that.setData({
            addressData: addressData,
            selRegion: {
              provinceId: 0, 
              cityId: 0, 
              provinceName: item.ProvinceName, 
              cityName: item.CityName,
              countyId: item.RegionId, 
              countyName:item.Name
            }
          })
        }        
      }
    })
  },
})
